import { getOrderLease, prepaymentPay } from "../../api/order";

Page({
  data: {
    order_id: '',
    billData: {},
    isView: false,
    order_lease: [],
    selectedList: [],
    totalPrice: 0
  },
  onLoad(options) {
    this.setData({ order_id: options.order_id, isView: !!options.isView });
    my.setNavigationBar({
      title: this.data.isView ? '账单详情' : '查看账单'
    });
    this.getData();
  },
  getStatusName(status) {
    switch (status) {
      case 0:
        return '未支付';
      case 1:
        return '已还款';
      case 2:
        return '已退款';
      case 3:
        return '已买断';
      case 4:
        return '已逾期';
      case 5:
        return '线下支付';

      default:
        break;
    }
  },
  getData() {
    getOrderLease(this.data.order_id).then(res => {
      let total = 0;
      const obj = { ...res };
      const list = [];
      obj.order_lease.forEach(element => {
        element.statusName = this.getStatusName(element.status);
        element.checked = false;
        if (element.status == 0 || element.status == 4) {
          element.checked = false;
          total += parseFloat(element.rent);
          list.push(element.id);
        }
      });
      // selectedList: list,
      this.setData({
        billData: obj || {},
        order_lease: obj.order_lease || [],
      
        totalPrice: total
      })
    })
  },
  onCheckChange(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { order_lease } = this.data;
    let total = 0;
    const list = [];
    order_lease.forEach(element => {
      if (element.id == id) {
        element.checked = value;
      }
      if (element.checked) {
        list.push(element.id);
        total = total + parseFloat(element.rent);
      }
    })
    this.setData({ order_lease, selectedList: list, totalPrice: total.toFixed(2) });
  },
  submit() {
    const { order_id: orderId, selectedList, order_lease } = this.data;
    for (let item of selectedList) {
      for (let ol of order_lease) {
        if (item == ol.id) {
          break;
        }
        //
      }
    }
    const leaseId = selectedList.join(',');
    prepaymentPay({ orderId, leaseId }).then(res => {
      if (res.tradeNo) {
        my.tradePay({
          tradeNO: res.tradeNo,
          success: (res) => {
            if (res.resultCode == 9000) {
              my.reLaunch({
                url: '../paySuccess/paySuccess?orderId=' + orderId
              });
            } else {
              my.showToast({
                type: 'fail',
                content: '支付失败，请稍后重试',
                duration: 1000,
              });
            }
          }
        });
      }
    })
  }
});
